<template>
  <div class="wrapper-list">
    <!-- 条件区 -->
    <el-row class="wrapper-condition">
      <el-col :span="4">
        <el-tree-select
          v-model="idCategory"
          :data="treeSelectData"
          :props="{ value: 'id', label: 'label' }"
          :render-after-expand="false"
          :current-node-key="0"
          value-key="id"
          placeholder="选择所属栏目"
          check-strictly
          @node-click="onListCategory"
          style="width: 300px"
        />
      </el-col>
      <el-col :span="12">
        <el-input v-model="keyword" placeholder="请输入关键字词" style="width: 300px">
          <template #append>
            <el-button :icon="Search" @click="onSearch()"> 搜索 </el-button>
          </template>
        </el-input>
        <el-button type="primary" @click="onListUnCheck()">
          <el-icon><List /></el-icon>待审
        </el-button>
        <el-button type="primary" @click="onListSigned()">
          <el-icon><List /></el-icon>已签发
        </el-button>
      </el-col>
      <el-col :span="8" style="text-align: right">
        <el-button v-if="articleStatus === 'uncheck'" type="primary" @click="onBatchSubmitCheck()">
          批量签发
        </el-button>
        <el-button v-if="articleStatus === 'signed'" type="primary" @click="onBatchCancelCheck()">
          批量撤回签发
        </el-button>
        <el-button type="primary" @click="onBatchMove()">
          <el-icon><Promotion /></el-icon>移动至
        </el-button>
        <el-tree-select
          v-model="idCategoryMove"
          :data="treeSelectData"
          :props="{ value: 'id', label: 'label' }"
          :render-after-expand="false"
          :current-node-key="0"
          value-key="id"
          placeholder="选择所属栏目"
          check-strictly
          style="width: 300px"
        />
      </el-col>
    </el-row>

    <!-- 列表区 -->
    <div class="wrapper-table">
      <el-table
        v-loading="flagLoading"
        :data="tblDataList"
        :header-cell-style="{ 'text-align': 'center' }"
        row-key="id"
        fit
        size="small"
        highlight-current-row
        style="width: 100%"
        @selection-change="onTblSelectChange"
      >
        <el-table-column v-if="articleStatus !== 'signed'" type="selection" align="center" width="30" />

        <el-table-column align="center" label="编号" width="50" prop="id" />

        <el-table-column label="栏目" align="center" width="90" prop="CategoryName" />

        <el-table-column label="标题">
          <template #default="scope">
            <el-link v-if="scope.row.UrlJump !== ''" :href="scope.row.UrlJump" target="_blank">
              {{ scope.row.Title }}
              <el-icon size="18" color="red">
                <Link />
              </el-icon>
            </el-link>
            <el-link v-else @click="showArticle(scope.row.id)">
              {{ scope.row.Title }}
              <el-icon v-if="scope.row.UrlTitlePic !== ''" size="18" color="red">
                <PictureFilled />
              </el-icon>
            </el-link>
            <span class="symbol-text">{{ formatSymbol(scope.row.SymbolShow) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="发布时间" align="center" width="150" prop="DtPublish" />

        <el-table-column label="责编" align="center" width="90" prop="EditorName" />

        <!--
        <el-table-column label="状态" align="center" width="60">
          <template #default="scope">
            <div v-html="formatStatus(scope.row.Status)"></div>
          </template>
        </el-table-column>
        <el-table-column label="签发" align="center" width="60" prop="SignerName" />
        -->

        <el-table-column label="浏览量" align="center" width="60" prop="Click" />

        <el-table-column width="120" align="center" label="操作">
          <template #default="scope">
            <div class="wrapper-op">
              <a
                v-if="articleStatus === 'uncheck'"
                class="ibtn ibtn-green"
                title="签发"
                @click="onSubmitSign(scope.row.id)"
              >
                <el-icon><View /></el-icon>
              </a>
              <a
                v-if="articleStatus === 'signed'"
                class="ibtn ibtn-red"
                title="撤回签发"
                @click="onUnCheck(scope.row.id)"
              >
                <el-icon><TopLeft /></el-icon>
              </a>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区 -->
    <div class="wrapper-pager">
      <el-pagination
        :current-page="pageCurrent"
        :page-sizes="pageSizeArrray"
        :page-size="pageSize"
        :total="recordCount"
        :page-count="pageCount"
        background
        small
        layout="prev, pager, next, jumper, sizes"
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
      />
    </div>

    <!-- 显示文章内容 -->
    <el-dialog v-model="flagDialogShow" :title="article.title" width="60%" :close-on-click-modal="false">
      <div class="wrapper-article">
        <h4>{{ article.Title }}</h4>
        <p class="info">发布时间：{{ article.DtPublish }} 作者：{{ article.Author }}</p>
        <div v-html="article.Content"></div>
      </div>
      <template #footer>
        <el-button type="primary" @click="flagDialogShow = false">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getAdminId } from '@/utils/common'
import { toastSuccess, toastError } from '@/utils/toast'
import { getLStorageObj } from '@/utils/web-storage'
import { AryToTree } from '@/utils/array'

import store from '@/store'
import { defineComponent, ref, onMounted } from 'vue'
export default defineComponent({
  name: 'ArticleListPageView',
  components: {},
  setup() {
    const idAdmin = ref(0)
    const idCategory = ref(2)
    const idCategoryMove = ref(2)
    const treeSelectData = ref([])
    // 分页列表数据的类型 CATEGORY:根据栏目id SEARCH:根据关键字词搜索 RECYCLE:回收站文章
    const type = ref('CATEGORY')
    const articleStatus = ref('uncheck')
    const articleIds = ref('')
    const keyword = ref('')
    const tblDataList = ref([])
    const flagLoading = ref(true)
    const pageCurrent = ref(1)
    const pageSize = ref(20)
    const pageSizeArrray = ref([10, 20, 30, 40])
    const recordCount = ref(0)
    const pageCount = ref(1)
    // 文章预览对话框
    const flagDialogShow = ref(false)
    const article = ref({})
    // 是否带标题图和标题视频
    const flagTitleImg = ref(false)
    const flagTitleVideo = ref(false)

    const getIdAdmin = () => {
      idAdmin.value = getAdminId()
    }
    // 得到所有文章分类
    const listCategory = () => {
      treeSelectData.value = AryToTree(getLStorageObj('AllCategory'), 2)
    }
    // 分页获取某栏目下文章列表
    const onListCategory = (category) => {
      type.value = 'CATEGORY'
      idCategory.value = category.id === 2 ? 0 : category.id
      pageCurrent.value = 1
      pageSize.value = 20
      listPage()
    }
    // 根据指定条件搜索文章
    const onSearch = () => {
      if (keyword.value === '') {
        toastError('请输入关键字词！')
        return
      }
      type.value = 'SEARCH'
      listPage()
    }
    // 得到所有已提交审核的分页数据
    const onListUnCheck = () => {
      type.value = 'CATEGORY'
      articleStatus.value = 'uncheck'
      pageCurrent.value = 1
      pageSize.value = 20
      listPage()
    }
    // 得到所有已签发分页数据
    const onListSigned = () => {
      type.value = 'CATEGORY'
      articleStatus.value = 'signed'
      pageCurrent.value = 1
      pageSize.value = 20
      listPage()
    }
    // 批量签发
    const onBatchSign = () => {
      if (articleIds.value === '') {
        toastError('请选择要提交审核的文章！')
        return
      }
      const paramsJson = {
        AdminId: idAdmin.value,
        ArticleIds: articleIds.value,
        Action: 'signed',
      }
      store
        .dispatch('article/batchPatchStatus', paramsJson)
        .then(() => {
          toastSuccess('签发成功！')
          listPage()
        })
        .catch(() => {})
    }
    // 批量撤回签发
    const onBatchUnCheck = () => {
      if (articleIds.value === '') {
        toastError('请选择要撤回签发的文章！')
        return
      }
      const paramsJson = {
        AdminId: idAdmin.value,
        ArticleIds: articleIds.value,
        Action: 'uncheck',
      }
      store
        .dispatch('article/batchPatchStatus', paramsJson)
        .then(() => {
          toastSuccess('撤回签发成功！')
          listPage()
        })
        .catch(() => {})
    }
    // 批量移动
    const onBatchMove = () => {
      if (articleIds.value === '') {
        toastError('请选择要移动的文章！')
        return
      }
      if (idCategoryMove.value === 2) {
        toastError('请选择要移动的栏目！')
        return
      }
      const paramsJson = {
        CategoryId: idCategoryMove.value,
        ArticleIds: articleIds.value,
      }
      store
        .dispatch('article/batchMove', paramsJson)
        .then(() => {
          toastSuccess('移动文章成功！')
          listPage()
        })
        .catch(() => {})
    }
    // 列出文章列表
    const listPage = () => {
      if (type.value === 'CATEGORY') {
        listPageCategory()
      } else if (type.value === 'SEARCH') {
        listPageSearch()
      } else {
        listPageCategory()
      }
    }
    // 根据栏目id获取文章分页数据
    const listPageCategory = () => {
      flagLoading.value = true
      const paramsJson = {
        PageCurrent: pageCurrent.value,
        PageSize: pageSize.value,
        Status: articleStatus.value,
        CategoryId: idCategory.value === 2 ? 0 : idCategory.value,
      }
      store
        .dispatch('article/listPageChecker', paramsJson)
        .then((response) => {
          flagLoading.value = false
          tblDataList.value = response.ListData
          recordCount.value = Number(response.RecordCount)
          pageCount.value = response.PageCount
        })
        .catch(() => {
          flagLoading.value = false
        })
    }
    // 分页获取标题包含某关键字词的文章列表
    const listPageSearch = () => {
      flagLoading.value = true
      const paramsJson = {
        PageCurrent: pageCurrent.value,
        PageSize: pageSize.value,
        Keyword: keyword.value,
      }
      store
        .dispatch('article/searchChecker', paramsJson)
        .then((response) => {
          flagLoading.value = false
          tblDataList.value = response.ListData
          recordCount.value = Number(response.RecordCount)
          pageCount.value = response.PageCount
        })
        .catch((error) => {
          flagLoading.value = false
          console.log('分页获取标题包含某关键字词的文章列表出现错误：', error)
        })
    }
    // 选择多条表格记录时
    const onTblSelectChange = (rows) => {
      let ids = []
      for (let i = 0; i < rows.length; i++) {
        ids.push(rows[i].id)
      }
      articleIds.value = ids.toString()
    }
    // 点击每页记录数大小下拉菜单
    const onSizeChange = (val) => {
      pageSize.value = val
      listPage()
    }
    // 点击分页页码
    const onCurrentChange = (val) => {
      pageCurrent.value = val
      listPage()
    }
    // 提交签发
    const onSubmitSign = (idArticle) => {
      const paramsJson = {
        ArticleId: idArticle,
        AdminId: idAdmin.value,
        Action: 'signed',
      }
      store
        .dispatch('article/patchStatus', paramsJson)
        .then(() => {
          toastSuccess('签发成功！')
          listPage()
        })
        .catch(() => {})
    }
    // 撤销签发
    const onUnCheck = (idArticle) => {
      const paramsJson = {
        ArticleId: idArticle,
        AdminId: idAdmin.value,
        Action: 'uncheck',
      }
      store
        .dispatch('article/patchStatus', paramsJson)
        .then(() => {
          toastSuccess('撤销签发成功！')
          listPage()
        })
        .catch(() => {})
    }
    const showArticle = (idArticle) => {
      store
        .dispatch('article/queryById', idArticle)
        .then((response) => {
          flagDialogShow.value = true
          article.value = response
        })
        .catch((error) => {
          console.log('得到文章详情出现错误：', error)
        })
    }
    const formatSymbol = (symbol) => {
      if (!symbol) return ''
      // indexOf() 方法返回数组中某个指定的元素位置
      const symbolShow = symbol.split(',')
      let result = ''
      if (symbolShow.indexOf('a') !== -1) {
        result += '[特荐]'
      }
      if (symbolShow.indexOf('b') !== -1) {
        result += '[加粗]'
      }
      if (symbolShow.indexOf('c') !== -1) {
        result += '[推荐]'
      }
      if (symbolShow.indexOf('f') !== -1) {
        result += '[幻灯]'
      }
      if (symbolShow.indexOf('h') !== -1) {
        result += '[头条]'
      }
      if (symbolShow.indexOf('p') !== -1) {
        result += '[图片]'
      }
      if (symbolShow.indexOf('s') !== -1) {
        result += '[滚动]'
      }
      return result
    }
    // 格式化文章状态： 0：草稿 1：删除 2：待审 3：已审 4：已签发 5：已生成静态文件
    const formatStatus = (statusCode) => {
      let html = ''
      if (statusCode === '0') {
        html = '<span class="blue">草稿</span>'
      } else if (statusCode === '1') {
        html = '<span class="red">删除</span>'
      } else if (statusCode === '2') {
        html = '<span class="blue-light">待审</span>'
      } else if (statusCode === '3') {
        html = '<span class="blue-dark">已审</span>'
      } else if (statusCode === '4') {
        html = '<span class="green-light">已签发</span>'
      } else if (statusCode === '5') {
        html = '<span class="green-dark">已生成</span>'
      } else {
        html = '<span class="red">未知</span>'
      }
      return html
    }

    onMounted(() => {
      getIdAdmin()
      listCategory()
      onListUnCheck()
    })

    return {
      // 查询分页数据的类型 all:所有文章 category:根据栏目id keyword:根据关键字词
      type,
      articleStatus,
      articleIds,
      keyword,
      idAdmin,
      idCategory,
      idCategoryMove,
      tblDataList,
      treeSelectData,
      flagLoading,
      pageCurrent,
      pageSize,
      pageSizeArrray,
      recordCount,
      pageCount,
      flagDialogShow,
      article,
      flagTitleImg,
      flagTitleVideo,
      getIdAdmin,
      listCategory,
      onListCategory,
      onSearch,
      onListUnCheck,
      onListSigned,
      onBatchSign,
      onBatchUnCheck,
      onBatchMove,
      listPage,
      listPageCategory,
      listPageSearch,
      onTblSelectChange,
      onSizeChange,
      onCurrentChange,
      onSubmitSign,
      onUnCheck,
      showArticle,
      formatSymbol,
      formatStatus,
    }
  },
})
</script>

<style lang="scss" scoped>
.wrapper-list .wrapper-condition {
  padding-bottom: 1.2rem;
  margin-bottom: 1.2rem;
}
.icon {
  display: inline-block;
  width: 1.5rem;
  height: 1.5rem;
  vertical-align: middle;
  margin-left: 0.6rem;
  .svg-icon {
    width: 1.5rem;
    height: 1.5rem;
  }
}
.symbol-text {
  display: inline-block;
  vertical-align: middle;
  color: red;
  line-height: 1.8rem;
  margin-left: 0.6rem;
}
.wrapper-article .info {
  text-align: center;
  font-size: 12px;
  line-height: 30px;
  color: #cccccc;
}
</style>
